﻿using LS.Screening.UI.Common;
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
using System.Globalization;
using System.Reflection;
using System.Windows;
using System.Windows.Input;

namespace LS.Screening.UI.Startup
{
    public class LoginViewModel : ViewModel
    {
        /// <summary>
        /// 账号
        /// </summary>
        private string account = "admin";
        public string Account { get => account; set => this.RaiseAndSetIfChanged(ref account, value); }

        /// <summary>
        /// 密码
        /// </summary>
        private string password = "admin@123";
        public string Password { get => password; set => this.RaiseAndSetIfChanged(ref password, value); }

        /// <summary>
        /// Token
        /// </summary>
        [Reactive]
        public string Token { get; set; }

        /// <summary>
        /// 标题
        /// </summary>
        [Reactive]
        public string Title { get; set; }

        /// <summary>
        /// 登录
        /// </summary>
        public ICommand LoginCommand { get; set; }

        /// <summary>
        /// 构造函数
        /// </summary>
        public LoginViewModel() : base()
        {
            LoginCommand = ReactiveCommand.Create(Login);
        }

        public override async Task Init()
        {
            await base.Init();
        }

        /// <summary>
        /// 登录方法
        /// </summary>
        private async Task Login()
        {
            MessageHelper.SendMessage("登录成功");
            var mainViewStr = ClientConfig.Instance.MainWindow.Split(";");
            if (!string.IsNullOrEmpty(Account) && !string.IsNullOrEmpty(Password))
            {
                await App.Current.Dispatcher.InvokeAsync(() =>
                {
                    var mainViewStr = ClientConfig.Instance.MainWindow.Split(";");
                    var mainWindow = (Window)Assembly.LoadFrom(mainViewStr[0])
                    .CreateInstance(
                        mainViewStr[1],
                        false,
                        BindingFlags.Default,
                        null,
                        new object[] {
                          this.Token,
                          ClientConfig.Instance.ServerUrl,
                          this.Title,
                          ClientConfig.Instance.AuthServerUrl
#if DEBUG
                          ,false
#else
                          ,false
#endif
                        },
                       CultureInfo.CurrentCulture, null);
                    this.Close();
                    App.Current.MainWindow = mainWindow;
                    mainWindow.Show();
                });
            }
        }
    }
}
